<script setup lang="ts">
import { ref, watch, nextTick } from "vue";
import { useSystemStoreWithOut } from "@/store/modules/system";
import { storeToRefs } from "pinia";
import { useMessage } from "@/hooks/useMessage";
import { getOutboundQueryMaterialStock } from "@/api/outbound";
import { add } from "@/utils/caculate";
import ChooseMaterialDialog from "@/components/ChooseMaterialDialog";
import { max } from "@pureadmin/utils";

const ADD_LINE_HEIGHT = 40; // 添加行高度
const ROW_HEIGHT = 55; // table单行高度
const MAX_NUM = 9999999;
const { createConfirm, createNotification } = useMessage();
const systemStore = useSystemStoreWithOut();
const { materialTypeList } = storeToRefs(systemStore);

const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  tableHeight: {
    type: Number,
    default: 0
  },
  preWarehouseCode: {
    type: String,
    default: ""
  }
});
const curRow = ref({});
const curRowIndex = ref(null);
const editMaterialRef = ref();
const tableData = ref([]);
const tableRef = ref();
const formRef = ref();

const diyRow = {
  materialCode: "", // 物料编码
  materialSpecsId: "", // 物料规格id
  materialName: "", // 物料名称
  materialType: "", // 物料类型
  materialSpecs: "", // 物料规格
  unit: "", // 单位
  overReceiveFlag: 0, // 超领标志
  maxNum: 0, // 最大可出库数量
  num: 0, // 本次出库数量
  overReceiveNum: 0, // 超领数量
  overReceiveWarehouseCode: "" // 超额处置仓库
};

const emits = defineEmits(["setTotalData"]);

watch(
  () => props.list,
  (newVal: any) => {
    tableData.value = newVal;
  },
  { deep: true }
);

watch(
  () => props.preWarehouseCode,
  (newVal: any, oldVal: any) => {
    if (!oldVal) return;
    tableData.value = [];
    curRow.value = {};
    curRowIndex.value = null;
  }
);

watch(
  tableData,
  (newVal: any) => {
    emits("setTotalData", newVal);
  },
  { deep: true }
);

const handleRowClick = (row: any) => {
  curRow.value = row;
};

const addRow = () => {
  tableData.value.push(diyRow);
};

// 添加物料
const addMaterial = (selections: any) => {
  const results = selections.map(val => {
    return {
      materialCode: val.materialCode,
      materialSpecsId: val.materialSpecsId,
      warehouseCode: props.preWarehouseCode
    };
  });
  getOutboundQueryMaterialStock(results).then(rsp => {
    const res = rsp.data || [];
    res.unshift(curRowIndex.value, 1);
    Array.prototype.splice.apply(tableData.value, res);
    nextTick(() => {
      tableRef.value.setScrollTop(
        add(curRowIndex.value, res.length) * ROW_HEIGHT
      );
    });
  });
};

const handleDeleteRow = (i: number) => {
  createConfirm({
    message: "确定删除该行吗？",
    center: false
  }).then(() => {
    tableData.value.splice(i, 1);
  });
};

const chooseMaterial = (row: any, i: number) => {
  if (!props.preWarehouseCode) {
    createNotification({
      message: "请先选择出库仓库名称",
      type: "error"
    });
    return;
  }
  curRow.value = row;
  curRowIndex.value = i;
  editMaterialRef.value.open();
};

const validateForm = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid: any) => {
      if (valid) {
        resolve(true);
      } else {
        reject(false);
      }
    });
  });
};

defineExpose({
  getTableData: () => {
    return tableData.value;
  },
  validateForm
});
</script>

<template>
  <el-form ref="formRef" :model="tableData" inline>
    <el-table
      ref="tableRef"
      class="tableBox"
      :data="tableData"
      style="width: 100%"
      :height="tableHeight - ADD_LINE_HEIGHT"
      @row-click="handleRowClick"
    >
      <el-table-column type="index" label="序号" min-width="80px" />
      <el-table-column
        prop="materialCode"
        label="物料编码"
        min-width="128px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="materialName"
        label="物料名称"
        min-width="120px"
        show-overflow-tooltip
      />
      <el-table-column
        label="物料类型"
        prop="materialType"
        min-width="104px"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-text>{{
            materialTypeList.find(
              val => val.dictLabelValue == scope.row.materialType
            )?.dictLabelName
          }}</el-text>
        </template>
      </el-table-column>
      <el-table-column
        prop="materialSpecs"
        label="物料规格"
        min-width="200px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="unit"
        label="单位"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column prop="num" label="调出数量" min-width="136px">
        <template #default="{ row, $index }">
          <el-form-item :prop="`[${$index}].num`" required>
            <el-input-number
              v-model="row.num"
              :max="MAX_NUM"
              :min="0"
              :controls="false"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="136px">
        <template #default="{ row, $index }">
          <el-button link type="primary" @click="chooseMaterial(row, $index)">
            选择物料
          </el-button>
          <el-button link type="danger" @click="handleDeleteRow($index)">
            删除行
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div
      class="addRow cursor-pointer text-center leading-[30px] h-[30px] border border-solid outline-[#eeeeee] mt-[10px] rounded-[4px]"
      @click="addRow"
    >
      <span class="text-[14px]">+ 添加行</span>
    </div>
    <ChooseMaterialDialog ref="editMaterialRef" @submit="addMaterial" />
  </el-form>
</template>
<style lang="scss" scoped>
.tableBox {
  .el-input {
    --el-input-width: 100% !important;
  }
  .el-form-item {
    margin-bottom: 0;
    margin-right: 0;
  }
}
.addRow {
  overflow: hidden;
  user-select: none;
  &:hover {
    color: $main-color;
  }
}
</style>
